﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tasker.Infrastructure.Repositories.Base;
using Tasker.Repositories.Entities;
using Tasker.Composition;

namespace Tasker.Repositories.Base
{
    sealed class EFContextManager : IContextManager
    {
        bool _scopeMode;
        bool _errorDetected;
        EntitiesContext _context = Resolver.Resolve<EntitiesContext>();

        public void Begin()
        {
            _scopeMode = true;
        }

        public void Commit()
        {
            // if scope mode then commit all changes. Otherwise they were already committed.
            if (_scopeMode)
                DatabaseSave();
        }

        public void Save()
        {
            if (_scopeMode)	// if we are in scope, then don't submit the changes - it will be done by Commit()
                return;

            if (_errorDetected)	// if error previously occurred, then do not commit.
                return;
            DatabaseSave();
            // if it is not a scope mode (transaction script mode, in fact) then submit changes.

        }

        private void DatabaseSave()
        {
            try
            {
                _context.SaveChanges();
            }
            catch (Exception exc)
            {
                if (exc.ToString().Contains("UX_Users_Nick"))
                {
                    //var errors = Resolver.Resolve<IErrorAggregator>();
                    //errors.AddError(new ErrorInfo("Nick", "Nick already registred"));
                }
                else
                    if (exc.ToString().Contains("UX_Users_EMail"))
                    {
                        //var errors = Resolver.Resolve<IErrorAggregator>();
                        //errors.AddError(new ErrorInfo("EMail", "EMail already registred"));
                    }
                    else
                        throw exc;
                _errorDetected = true;
            }
        }
    }
}
